package world.xuewei.component;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import world.xuewei.component.utils.JwtUtil;
import world.xuewei.model.entity.R;
import world.xuewei.model.entity.UserBase;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 *
 * @author XUEW
 */
public class LoginHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 处理跨域预检请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        // 设置跨域响应头
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Max-Age", "3600");

        // 从请求头获取token
        String token = request.getHeader("token");

        // 检查token是否存在
        if (!StringUtils.hasText(token)) {
            handleUnauthorized(response, "请先登录");
            return false;
        }

        // 验证token
        Claims claims = JwtUtil.verifyToken(token.replace("Bearer ", ""));
        if (claims == null) {
            handleUnauthorized(response, "token无效或已过期");
            return false;
        }

        // 将用户信息存入request属性中，供后续使用
        request.setAttribute("userId", claims.getSubject());
        request.setAttribute("username", claims.get("username"));
        return true;
    }

    private void handleUnauthorized(HttpServletResponse response, String message) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        R result = R.error()
                .code(401)
                .message(message);
        new ObjectMapper().writeValue(response.getWriter(), result);
    }
}
